﻿using BLL;
using Mapster;
using Microsoft.VisualBasic;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.基本资料;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.设置窗体;
using 纺织贸易管理系统.选择窗体;

namespace 纺织贸易管理系统.新增窗体
{
    public partial class 原料盘盈单 : Form
    {
        public FormUseful  useful = FormUseful.新增;
        public List<ImportAndExportOfRawMaterials> danjumingxitables = new List<ImportAndExportOfRawMaterials>();
        public int rowindex;
        public DanjuTable danju = new DanjuTable();
        public 原料盘盈单()
        {
            InitializeComponent();         
            CreateGrid.Create(this.Name, gridView1);
            try
            {
                gridView1.Columns["Num"].ColumnEdit = ButtonEdit1;
                gridView1.IndicatorWidth = 30;
            }
            catch
            {
                配置列ToolStripMenuItem_Click(null, null);
            }
        }

        private void 配置列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView1) { formname = this.Name, Obj = new ImportAndExportOfRawMaterials() };
            fm.ShowDialog();
        }

        private void ButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var fm = new 原料选择();
                fm.ShowDialog();
                var rowhandle = gridView1.FocusedRowHandle;
                foreach(var raw in fm.SelecRaws )
                {
                    raw.Adapt(danjumingxitables[rowhandle]);
                    rowhandle++;
                }
                gridControl1.RefreshDataSource();
                gridView1.CloseEditor();
            }
        }

  

        private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.DeleteRow(gridView1.FocusedRowHandle);
        }

        private void 添加行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            danjumingxitables.Add(new ImportAndExportOfRawMaterials() { DocNum = txtdanhao.Text });
            gridControl1.RefreshDataSource();
        }

        private void 复制行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rowindex  =gridView1.FocusedRowHandle;
        }

        private void 粘贴行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyRow.Copy<ImportAndExportOfRawMaterials>(danjumingxitables, rowindex, gridView1, gridView1.FocusedRowHandle, this);
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                danjumingxitables[gridView1.FocusedRowHandle].Total = danjumingxitables[gridView1.FocusedRowHandle].Price * danjumingxitables[gridView1.FocusedRowHandle].InventoryQuantity;
                gridControl1.RefreshDataSource();
            }
            catch 
            {
                MessageBox.Show("请输入数字。计算错误");
            }
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.CloseEditor();
           
            if(danjumingxitables.Where (x=>x.Num !=null).ToList ().Count ==0)
            {
                ShowMessageBox.ShowErrorBox (  "没有检测到任何布料信息.请选择相应的布料后再保存！");
                return;
            }

            danju.bz = txtbeizhu.Text;
            danju.dh = txtdanhao.Text;
            danju.djlx = DanjuLeiXing.原料盘盈单 ;
            danju.rq = dateEdit1.DateTime.Date ;
            danju.je = danjumingxitables.Sum(x => x.Total) ;           
            danju.TotalMishu = danjumingxitables.Sum(x => x.InventoryQuantity);
            danju.own = Tools.CurrentUser.user.YHBH;
            danju.zhuangtai = "未审核";
            try
            {
                Connect.dbcontext.BeginTran();
                if (useful == FormUseful.新增)
                {
                    原料入库BLL.保存单据(danju, danjumingxitables.Where(x => !string.IsNullOrEmpty(x.Num)).ToList());
                }
                else
                {
                    原料入库BLL.修改单据(danju, danjumingxitables.Where(x => !string.IsNullOrEmpty(x.Num)).ToList());
                }
                Connect.dbcontext.CommitTran();
                AlterDlg.Show("保存成功！"); 
                //清空所有控件
                Init();
            }
            catch (Exception ex)
            { 
                Connect.dbcontext.RollbackTran();
                ShowMessageBox.ShowErrorBox("保存的时候发送了错误" + ex.Message);
               
            }
           
        }
        private void Init()
        { 
            foreach (Control  c in this.groupControl1.Controls  )
            {
                if(c is DevComponents.DotNetBar.Controls.TextBoxX||c is DevExpress.XtraEditors.ButtonEdit)
                {
                    c.Text = "";
                }
            } 
            dateEdit1.DateTime  = DateTime.Now;
            txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.原料盘盈单, dateEdit1.DateTime, DanjuLeiXing.原料盘盈单);        
            danjumingxitables.Clear();
           danjumingxitables = Connect.CreatConnect().Query<ImportAndExportOfRawMaterials> (x => x.DocNum == txtdanhao.Text);
            var length = danjumingxitables.Count;
            for (int i = 0; i < 30 - length; i++)
            {
                danjumingxitables.Add(new ImportAndExportOfRawMaterials() { DocNum = txtdanhao.Text });
            } 
            gridControl1.DataSource = danjumingxitables;
            gridControl1.RefreshDataSource();
            useful = FormUseful.新增;
        }

        private void 采购入库单_Load(object sender, EventArgs e)
        {
            if (useful == FormUseful.新增)
            {
                Init();
            }
            else
            {
                Edit();
                if(useful==FormUseful.查看 )
                {
                    保存ToolStripMenuItem.Enabled = false;
                }
            }
        }
        private void Edit()
        {
            txtdanhao.Text = danju.dh;
            txtbeizhu.Text = danju.bz;   
            dateEdit1.Text = danju.rq.ToShortDateString();
            danjumingxitables = Connect.dbcontext.Queryable<ImportAndExportOfRawMaterials>().Where(x => x.DocNum == txtdanhao.Text).ToList();
            var length = danjumingxitables.Count;
            for (int i = 0; i < 30 - length; i++)
            {
               danjumingxitables.Add(new ImportAndExportOfRawMaterials() { DocNum = txtdanhao.Text });
            }
            gridControl1.DataSource = danjumingxitables;
        }

       
        private void 采购入库单_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView1);
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            Print(PrintModel.Privew);
        }
        private void Print(PrintModel useful)
        {
            if (danjumingxitables.Where(x => x.Num != null).ToList().Count == 0)
            {
                ShowMessageBox.ShowErrorBox (  "没有检测到任何布料信息.请选择相应的布料后再保存！");
                return;
            }
            danju.bz = txtbeizhu.Text;
            danju.dh = txtdanhao.Text;
            danju.djlx = DanjuLeiXing.原料盘盈单;
            danju.rq = dateEdit1.DateTime.Date;
            danju.je = danjumingxitables.Sum(x => x.Total);
            danju.TotalMishu = danjumingxitables.Sum(x => x.InventoryQuantity);
            danju.own = Tools.CurrentUser.user.YHBH;
            danju.zhuangtai = "未审核";
            var ds = new DataSet();
            var danjutable = JsonConvert.DeserializeObject<DataTable>(Newtonsoft.Json.JsonConvert.SerializeObject(new List<DanjuTable>() { danju }));
            danjutable.TableName = "单据信息";
            ds.Tables.Add(danjutable);
            var mingxidt = JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(danjumingxitables.Where(x => !string.IsNullOrEmpty(x.Num)).ToList()));
            mingxidt.TableName = "单据明细";
            ds.Tables.Add(mingxidt);
            Tools.PrintHelper.PrintReport(useful, ds, ReportService.报表 + "\\原料领用单.frx");
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Print(PrintModel.Design);
        }
    }
}
